import {
  ds
} from "~/tools/data"
import {
  ui
} from "~/tools/ui"
import {
  checkTool
} from "~/tools/check"
import {
  pages
} from "~/tools/pages"
Page({
  data: {
    action: 'read',
    item: {}
  },
  async init() {
    const that = this,
      _ = ds.cmd
    ds.coll('module')
      .where({
        _id: _.eq(this.data.id)
      })
      .orderBy('pos', 'asc')
      .get({
        success: function (res) {
          that.setData({
            mod: res.data[0]
          })
        }
      });
  },
  addSwiper(e) {
    wx.navigateTo({
      url: '/pages/common/imgSelect/index',
    })
  },
  imgSelected(files, tag) {
    const {
      item
    } = this.data
    if (files?.length <= 0) return
    if (tag) { // edit
      const index = parseInt(tag)
      item.imgs[index] = files[0]
    } else {
      item.imgs = (item.imgs || []).concat(files)
    }
    this.setData({
      item
    })
  },
  editSwiper(e) {
    const index = ui.eventData(e, 'index')
    wx.navigateTo({
      url: `/pages/common/imgSelect/index?tag=${index}`,
    })
  },
  onDeleteTap(e) {
    const index = ui.eventData(e, 'index')
    const item = this.data.item
    item.imgs.splice(index, 1)
    this.setData({
      item
    })
  },
  backTap() {
    pages.back(pre => {
      pre.init()
    })
  },
  dayInputChange(e) {
    this.setData({
      'item.title': e.detail.value
    })
  },
  saveTap() {
    ui.loading();
    const {
      item
    } = this.data
    checkTool.check([{
      title: "标题",
      allowEmpty: false,
      value: item.title
    }])

    // console.log(item)
    item.date = Date.now()
    item.visible = (typeof item.visible == 'undefined' ? true : item.visible)
    ds.cloudUpdate('help', item._id, item, res => {
      ui.loading(false)
      const success = res.result.errMsg.endsWith(":ok")
      if (success) pages.back(prePage => {
        prePage.init()
      })
    })
  },
  onChangePosInput(e) {

    this.setData({
      'mod.pos': e.detail.value
    })
  },
  onLoad(option) {
    this.setData({
      item: JSON.parse(option.data ?? "{}"),
      action: option.action ?? 'read'
    });
    this.init();
  },
});